<?php
/* 
 *交易action 公共类：enter,sale。。。switch均可继承
 */
class TransAction extends CommonAction {
   
    public function _before_add(){
        $this->assign('users',getModelIdName('User'));
    }

    public function _before_edit(){
        $this->assign('users',getModelIdName('User'));
    }

   

    public function insert(){
       //TODO 重复退货的控制
         $model = $this->getActionName();
         $Model = D($model);
         $pid = $_POST['product_id'];
         if(!$pid)
            $this->error('请选择至少一个产品');
        if($pid != array_unique($pid))
          $this->error('您选择的产品存在重复，请去重后再操作！');

          $number = $_POST['number'];
          foreach ($number as $value) {
            if($value <0 )
              $this->error("产品数量必须大于0  ");
            break;
          }

          $specifications = $_POST['specification'];
          foreach ($specifications as $s) {
            if($s <1 )
              $this->error("必须选择规格！");
            break;
          }

        if(false == $Model->create()) {
            $this->error($Model->getError());
        }
        if(false !== $list = $Model->add()) {
            $this->__process_enter_detail($list);
            $mod_field = getModelName ($list, $model);
            $msg = '新增 '.$model.': '.$mod_field.' (编号：'.$list.')';
            A('Action')->writeLog($msg,'新增',$model,$list);
            $this->assign ( 'jumpUrl', '__URL__' ); //return index list
            $this->success('添加成功');
        }
        else {
            $this->error('新增失败！');
        }
    }

   

    protected function __process_enter_detail($trans_id){
        $model = $this->getActionName();
        $m = strtolower($model);
        $data =array(
                'product_id'=>$_POST['product_id'],
                'number'=>$_POST['number'],
                $m.'_id'=>$trans_id,
                //$m.'_no' => getModelName($trans_id, $model,$m.'_no'),
        );

        $val_data = array();
        switch ($m) {
            case 'order':
                $val_data =array(
                        'price'=>$_POST['price'],
                        'unit_id'=>$_POST['unit_id'],
                        'logifee'=>$_POST['logifee'],
                        'specification'=>$_POST['specification'], 
                        'delivery_date'=>$_POST['delivery_date'],
                        'priority'=>$_POST['priority'], 
                        'cost'=>$_POST['dcost'],
                        'to_first_pay'=>$_POST['dto_first_pay'],
                        'status'=>$_POST['dstatus'],
                        'remark'=>$_POST['dremark'],
                        'logifee' => $_POST['logifee'],
                        'charge_man' => $_POST['user_id'] //charge man

                );
                break;
            case 'shipping':
            default:
                 $val_data =array(
                        'total'=>$_POST['total'],
                        'logifee'=>$_POST['logifee'],
                        'price'=>$_POST['price'],
                        'sum_total'=>$_POST['sum_total'],
                        'order_detail_id'=>$_POST['order_detail_id'],
                        'pack_type' => $_POST['pack_type'],
                        'pack_weight' => $_POST['pack_weight'],
                        'length' => $_POST['length'],
                        'width' => $_POST['width'],
                        'height' => $_POST['height'],
                        'pack_desc' => $_POST['pack_desc'],
                        'about_net_weight' => $_POST['about_net_weight']
                );
                break;
        }
        $data = array_merge($data,$val_data);
        
        $status =  $this->addDetail($data);
        if (!$status) {
            $this->errmsg .= "<br/>";
            $this->errmsg .=  '详情插入出现问题！';
        }
        return;
    }

    protected function addDetail($data){
       $small_count = count($data['product_id']);
           $detail_data = array();
           $new_id = 0; //插入的新数据ID
           //$model = M('Sale_detail');
           $big_m = $this->getActionName();
           $model = M($big_m.'_detail');
           $m = strtolower( $big_m );//变小写
           $total = 0; //total money @overview table 总金额= 总产品价+运费
           $cost = 0 ; //总成本价= 各个产品成本之和
           switch ($m) {
               case 'order': {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   'product_id'=> $data['product_id'][$i],
                                   'price'=> $data['price'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['price'][$i]*$data['number'][$i],
                                   'cost'=>empty($data['cost'][$i])? 0 : $data['cost'][$i],
                                   
                                   'priority'=>empty($data['priority'][$i])?0 : $data['priority'][$i],
                                   'logifee'=>empty($data['logifee'][$i])? 0 : $data['logifee'][$i],
                                   'to_first_pay'=>empty($data['to_first_pay'][$i])? 0 : $data['to_first_pay'][$i],
                                   'to_remain_pay'=>($data['price'][$i]*$data['number'][$i]+ $data['logifee'][$i] - $data['to_first_pay'][$i]),
                                   'should_pay'=> ($data['price'][$i]*$data['number'][$i]+ $data['logifee'][$i]),
                                   'unit_id'=>$data['unit_id'][$i],
                                    'specification'=>empty($data['specification'][$i])?0 : $data['specification'][$i], 
                                    'delivery_date'=>empty($data['delivery_date'][$i]) ? 0 : strtotime($data['delivery_date'][$i]), 
                                    'status'=>empty($data['status'][$i])? 0 : $data['status'][$i],
                                   'create_time'=> time(),
                                   'mano' => getModelName($data[$m.'_id'],$big_m,'mano').'-'.($i+1),
                                   'charge_man' => $data['charge_man']
                           );
                           if($small_count == 1) //只有一个，不要分单号
                              $detail_data['mano'] = getModelName($data[$m.'_id'],$big_m,'mano');

                           $new_id = $model ->add($detail_data);
                           if($new_id > 0)  //减去库存 未审批，不能立即减去库存。在发货时可判断
                               //$this->updateStock($data['product_id'][$i],$data['specification'][$i], 'out', $data['number'][$i]);
                           $total += $detail_data['total']+$detail_data['logifee'];//货款+运费
                           $cost += $detail_data['cost'] ; //订单总成本等于各小单成本之和TODO 将来小单变动时要相应调整
                           unset($detail_data);
                           $new_id = 0;
                       }
                       //更新大表总金额
                       M($big_m)->where('id = '.$data[$m.'_id'])->setField('total',$total);
                       $total = 0 ;
                       M($big_m)->where('id = '.$data[$m.'_id'])->setField('cost',$cost);
                       $cost = 0 ;
                       return true;
                   }
                   break;
               case 'shipping':
               default:
                   {
                       for( $i =0 ; $i<$small_count;$i++) {
                           $detail_data= array(
                                   $m.'_id'=> $data[$m.'_id'],
                                   'product_id'=> $data['product_id'][$i],
                                   'number'=> $data['number'][$i],
                                   'total' => $data['total'][$i],
                                   'order_detail_id' => $data['order_detail_id'][$i],
                                   'logifee'=>$_POST['logifee'][$i],
                                    'price'=>empty($_POST['price'][$i])? 0 : $_POST['price'][$i],
                                    'sum_total'=>$_POST['sum_total'][$i],
                           );
                           $new_id = $model ->add($detail_data);
                           if($new_id > 0) {
                              //将销售分单状态置为 5= 打包完成，单据待制作
                              M('Order_detail')->where('id = '.$data['order_detail_id'][$i])->setField('status',5);
                            //减去库存
                              $specification = getModelName($data['order_detail_id'][$i],'Order_detail','specification');
                               $this->updateStock($data['product_id'][$i], $specification ,'out', $data['number'][$i]);
                               
                               $total += $detail_data['total'];
                               unset($detail_data);
                               $new_id = 0;
                           } 
                       }
                       //package number
                       $pack_count = count($data['pack_type']);

                       $pack_data = array();
                       $tmp_weight = 0; //各毛重之和
                       $tmp_net_weight = 0; //各净重之和
                        for( $i =0 ; $i<$pack_count;$i++) {
                          if($data['pack_type'][$i] <1 )
                            continue;
                            $pack_data = array(
                                'shipping_id' => $data['shipping_id'],
                                'pack_type' => $data['pack_type'][$i],
                                'pack_weight' => $data['pack_weight'][$i],
                                'length' => $data['length'][$i],
                                'width' => $data['width'][$i],
                                'height' => $data['height'][$i],
                                'pack_desc' => $data['pack_desc'][$i],
                                'about_net_weight' => $data['about_net_weight'][$i]
                            );
                            $tmp_weight += $data['pack_weight'][$i];
                            $tmp_net_weight += $data['about_net_weight'][$i];

                            M('Package')->add($pack_data);
                        }

                       //TODO 若全部子订单已经发货，将销售订单状态改为已发货，
                       //更新大表总金额
                        $setData = array(
                          'total' => $total,
                          'weight' => $tmp_weight,
                          'net_weight' => $tmp_net_weight
                          );
                       M($big_m)->where('id = '.$data[$m.'_id'])->save( $setData ); 
                       $total = 0 ;
                       return true;
                   }
                   break;
           }
           
   }

   /**
    *更新库存操作，如果存在对应产品编号，则在记录上进行增减；如果无，则增加记录
    *
    * @param <type> $product_id 产品编号
    * @param <type> $specification 产品规格
    * @param <type> $type 默认为in，入库，增加库存
    * @param <int> $number 数量
    */
   public function updateStock($product_id,$specification,$type='in',$number){
       $map = array(
           'product_id' => $product_id,
           'specification' => $specification,
       );
       $stock = M('Stock');
        $pstock = $stock->where($map)->find();
        
        //在原来基础上增加或改变
        if(is_array($pstock)){
            switch ($type){
                 case 'out':{
                     $old_number = $stock->where($map)->getField('number');
                     if($old_number < $number )
                         $stock->setDec('number',$map,$old_number);
                     else
                        $stock->setDec('number',$map,$number);
                    break;
                 }

                //入库
                case 'in':
                default:
                    $stock->setInc('number',$map,$number);
            }
        }else{//空记录
             switch ($type){
                 case 'out':{
                     $product = getModelName ($product_id, 'Product');
                     $msg = '试图从仓库中取出产品'.$product.' (编号：'.$product_id.')  数量为'.$number.',而该产品无库存记录 ！';
                     A('Action')->writeLog($msg,'异常','Stock',0);
                    break;
                 }
                //入库
                case 'in':
                default:
                {
                    $map['number'] = $number;
                    $stock->add($map);
                }
                    
            }
        }
   }

}
?>
